package table_user

import (
	"time"

	"gitee.com/klein-x/biz/model/mysql/table"
	"gitee.com/klein-x/biz/module/db/mysql"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"gorm.io/gorm"
)

const tableName = "user"

type User struct {
	UUID      string         `gorm:"primaryKey;type:char(36);unique;not null;comment:'UUID'"`
	Mobile    string         `gorm:"type:varchar(20);unique;not null;comment:'手机号'"`
	Name      string         `gorm:"type:varchar(60);not null;comment:'用户名'"`
	Password  string         `gorm:"type:varchar(32);not null;comment:'密码'"`
	Type      string         `gorm:"type:char(1);not null;default:'0';comment:'身份类型,normal 0,admin 1'"`
	CreatedAt time.Time      `gorm:"not null;comment:'创建时间'"`
	UpdatedAt time.Time      `gorm:"not null;comment:'更新时间'"`
	DeletedAt gorm.DeletedAt `gorm:"comment:'软删除时间'"`
}

func (User) TableName() string {
	return tableName
}

// 根据ID查询正常用户
func UserGetByID(id string) (*User, error) {
	db := mysql.GetGlobalDB()
	var user User
	return table.SelectCheck(&user, db.Where("uuid = ? AND type = ?", id, "0").First(&user))
}

// 通过ID查询所有用户（包括已删除的）
func UserGetByIDWithDeleted(id string) (*User, error) {
	db := mysql.GetGlobalDB()
	var user User
	return table.SelectCheck(&user, db.Unscoped().Where("uuid = ?", id).First(&user))
}

// 通过手机号查询正常用户
func UserGetByMobile(mobile string) (*User, error) {
	db := mysql.GetGlobalDB()
	var user User
	return table.SelectCheck(&user, db.Where("mobile = ? AND type = ?", mobile, "0").First(&user))
}

// 通过手机号查询所有用户（包括已删除的）
func UserGetByMobileWithDeleted(mobile string) (*User, error) {
	db := mysql.GetGlobalDB()
	var users User
	return table.SelectCheck(&users, db.Unscoped().Where("mobile = ?", mobile).Find(&users))
}

// 通过UUID查询正常的管理员用户
func UserGetByIDWithAdmin(uuid string) (*User, error) {
	db := mysql.GetGlobalDB()
	var user User
	return table.SelectCheck(&user, db.Where("uuid = ? AND type = ?", uuid, '1').First(&user))
}

// 插入用户
func UserInsert(user User) error {
	db := mysql.GetGlobalDB()
	hlog.Debug(user)
	return table.InsertCheck(db.Create(&user))
}

// 更新用户名
func UserUpdateUsernameById(id string, newUsername string) error {
	db := mysql.GetGlobalDB()
	return table.UpdateCheck(db.Model(&User{}).Where("uuid = ?", id).Update("name", newUsername))
}

// 更新用户密码
func UserUpdatePasswordById(id string, newPassword string) error {
	db := mysql.GetGlobalDB()
	return table.UpdateCheck(db.Model(&User{}).Where("uuid = ?", id).Update("password", newPassword))
}

func UserRestoreById(id string) error {
	db := mysql.GetGlobalDB()
	return table.UpdateCheck(db.Model(&User{}).Unscoped().Where("uuid = ?", id).UpdateColumn("deleted_at", gorm.DeletedAt{}))
}
